package com.ctg.itrdc.k8sconsole.service.impl;

import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.ctg.itrdc.imageconsole.common.util.HttpRequestUtil;
import com.ctg.itrdc.imageconsole.data.dao.IClusterConfigDao;
import com.ctg.itrdc.imageconsole.data.dao.IK8sAlertDao;
import com.ctg.itrdc.imageconsole.data.dto.K8sAlertInfoDTO;
import com.ctg.itrdc.imageconsole.data.dto.K8sAlertRuleDTO;
import com.ctg.itrdc.imageconsole.data.entity.ClusterConfig;
import com.ctg.itrdc.imageconsole.util.RestClientUtils;
import com.ctg.itrdc.imageconsole.util.RestOperation;
import com.ctg.itrdc.imageconsole.util.SysManagerUtil;
import com.ctg.itrdc.k8sconsole.service.IAlarmService;
import com.ctg.itrdc.pasp.security.utils.WebUtils;
import com.ctg.itrdc.paspsdk.common.utils.file.PropertiesUtil;
import com.ctg.itrdc.paspsdk.common.utils.type.StringUtils;

/**
 * 
 * @description: k8s告警相关
 * @version: v1.0.0
 * @author: Piao.Wu
 * 
 *          Modification History: Date Author Version Description
 *          -----------------------------------------------------------------
 *          2016年8月18日 下午8:15:54 Piao.Wu v1.0.0 create
 *
 */
@Component("alarmService")
public class AlarmServiceImpl implements IAlarmService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());


	@Resource
	private IK8sAlertDao k8sAlertDao;
	@Resource
	private IClusterConfigDao clusterConfigDao;

	@Override
	public String getAlarms(String clusterCode, Long id, String perpage, String page, Boolean isactive,
			String alertType, String startTime, String endTime) throws Exception {
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);

		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("id", id);
		paraMap.put("perpage", Integer.valueOf(perpage));
		paraMap.put("page", Integer.valueOf(page));
		paraMap.put("isactive", isactive);
		paraMap.put("alertType", alertType);
		if (StringUtils.isNotEmpty(startTime)) {
			paraMap.put("startTime", Long.parseLong(startTime));
		}
		if (StringUtils.isNotEmpty(endTime)) {
			paraMap.put("endTime", Long.parseLong(endTime));
		}

		String urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "getAlarms.api");
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode);
		// 创建URL连接
		URL url = new URL(urlString);
		HttpRequestUtil requestUtil = new HttpRequestUtil(url);
		WebTarget target = HttpRequestUtil.target;
		Response response = target.request().post(Entity.entity(paraMap, MediaType.APPLICATION_JSON_TYPE));

		logger.info("========getAlarms.api返回的状态码:" + response.getStatus());
		return requestUtil.getResponseJsonData(response);
	}

	@Override
	public Map<String, Object> queryHeadK8sAlarms() {
		Long currentUserId = WebUtils.getCtgUser().getSysUserId();
		List<ClusterConfig> clusterConfigs = clusterConfigDao.jdbcFindList(currentUserId, SysManagerUtil.isRoleOfDockerManager());
		if (clusterConfigs == null || clusterConfigs.size() == 0) {
			return new HashMap<>();
		}
		List<String> clusterCodes = new ArrayList<>();
		for(ClusterConfig clusterConfig : clusterConfigs) {
			clusterCodes.add(clusterConfig.getClusterCode());
		}
		Map<String, Object> map = new HashMap<>();
		
		List<K8sAlertInfoDTO> alertInfoDTOs = k8sAlertDao.queryAlertInfosByClusterCodes(clusterCodes);
		ClusterConfig tmp = null;
		for(K8sAlertInfoDTO alertInfoDTO : alertInfoDTOs) {
			tmp = new ClusterConfig();
			tmp.setClusterCode(alertInfoDTO.getClusterCode());
			List<ClusterConfig> configs = clusterConfigDao.selectByExample(tmp);
			String cluserName = configs.size() == 0?null:configs.get(0).getClusterName();
			alertInfoDTO.setClusterName(cluserName);
		}
		map.put("list", alertInfoDTOs);
		map.put("count", k8sAlertDao.getAlertCountByClusterCodes(clusterCodes));
		
		return map;
	}

//	private static void sortByInsertTimeDesc(List<K8sAlertInfoDTO> listForSort) {
//		Collections.sort(listForSort, new Comparator<K8sAlertInfoDTO>() {
//			public int compare(K8sAlertInfoDTO o1, K8sAlertInfoDTO o2) {
//				if (o1.getInsertTime() < o2.getInsertTime()) {
//					return 1;
//				}
//				if (o1.getInsertTime() == o2.getInsertTime()) {
//					return 0;
//				}
//				return -1;
//			}
//		});
//	}



	@Override
	public String queryAlertTypes(String clusterCode) {
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);
		String urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "getAlertTypes.api");
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryAlertTypes时出现异常！", e);
		}
		return info;
	}

	@Override
	public String queryAlertRules(String clusterCode
			, final Long id, final String alertType
			, final Boolean isactive, final Long startTime, final Long endTime
			, final Integer perpage, final Integer page) {
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);
		String urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "getAlertRules.api");
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode);

		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.queryParam("id", id)
							.queryParam("alertType", alertType)
							.queryParam("isactive", isactive)
							.queryParam("startTime", startTime)
							.queryParam("endTime", endTime)
							.queryParam("perpage", perpage).queryParam("page", page)
							.request().get();
				}
			});
		} catch (Exception e) {
			logger.error("queryAlertRules时出现异常！", e);
		}
		return info;
	}

	@Override
	public void addAlertRule(String clusterCode, final K8sAlertRuleDTO alertRuleDTO)
			throws Exception {
		String urlString = null;
		urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "addAlertRule.api");
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode);
		try {
			RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().post(Entity.entity(alertRuleDTO, MediaType.APPLICATION_JSON_TYPE));
				}
			});
		} catch (Exception e) {
			throw new RuntimeException("addAlertRule时出现异常！", e);
		}
	}

	@Override
	public void modifyAlertRule(String clusterCode, final K8sAlertRuleDTO alertRuleDTO) throws Exception {
		String urlString = null;
		urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "alertRule.api");
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode, alertRuleDTO.getId());
		try {
			RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().put(Entity.entity(alertRuleDTO, MediaType.APPLICATION_JSON_TYPE));
				}
			});
		} catch (Exception e) {
			throw new RuntimeException("modifyAlertRule时出现异常！", e);
		}
	}

	@Override
	public void deleteAlertRule(String clusterCode, final K8sAlertRuleDTO alertRuleDTO) throws Exception {
		String urlString = null;
		urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "alertRule.api");
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode, alertRuleDTO.getId());
		try {
			RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().delete();
				}
			});
		} catch (Exception e) {
			throw new RuntimeException("deleteAlertRule时出现异常！", e);
		}
	}

	@Override
	public String queryAlertRule(String clusterCode, Long id) {
		String urlString = null;
		urlString = PropertiesUtil.getConfigValueCache("k8s.properties", "alertRule.api");
		ClusterConfig clusterConfig = clusterConfigDao.queryByClusterCode(clusterCode);
		urlString = MessageFormat.format(urlString, clusterConfig.getMonitorUrl(), clusterCode, id);
		String info = null;
		try {
			info = RestClientUtils.connect(urlString, new RestOperation() {

				@Override
				public Response request(WebTarget target) {
					return target.request().get();
				}
			});
		} catch (Exception e) {
			throw new RuntimeException("queryAlertRule时出现异常！", e);
		}
		return info;
	}

}
